package topk;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

/**
 * @author DCSGO
 * @version 1.0
 * https://leetcode.cn/problems/zui-xiao-de-kge-shu-lcof/description/
 */
public class Solution {
    public int[] getLeastNumbers(int[] arr, int k) {
        if(k==0){
            return new int[0];
        }

        Queue<Integer> minHeap = new PriorityQueue<Integer>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        //将前K个数入堆
        for (int i = 0; i < k; i++) {
            minHeap.offer(arr[i]);
        }
        for (int i = k; i < arr.length; i++) {
            //堆顶元素大于当前数
            if (minHeap.peek() > arr[i]) {
                //堆顶元素出堆 当前数入堆
                minHeap.poll();
                minHeap.offer(arr[i]);
            }
        }
        int[] res = new int[k];
        for (int i = 0; i < k; i++) {
            res[i] = minHeap.poll();
        }
        return res;
    }
}
